#include "qe_shell.h"
#include "qe_string.h"
#include "qe_driver.h"
#include "qe_argparse.h"




static qe_const_str usages[] = {
    "i2c [options] [[--] args]",
    "i2c [options]",
    QE_NULL,
};

static char current_device[16] = {"i2c0"};

static qe_ret action_set_current_device(qe_argparse *parser, qe_option *option)
{
    qe_sprintf(current_device, "%s", qe_option_string(option));
    qe_printf("set current i2c device %s\r\n", current_device);
    return qe_yield;
}

static qe_ret action_bus_detect(qe_argparse *parser, qe_option *option)
{
    int i;
    int n;
    qe_u8 addr;
    qe_u8 data;
    qe_i2c_message msgs[2];
    qe_i2c_bus *bus = qe_i2c_bus_find(current_device);

    msgs[0].flags = QE_I2C_WR;
    msgs[0].buf = QE_NULL;
    msgs[0].len = 0;
    msgs[1].flags = QE_I2C_RD;
    msgs[1].buf = &data;
    msgs[1].len = 1;    

    for (i=0; i<0x7f; i++) {
        msgs[0].addr = i;
        msgs[1].addr = i;
        n = qe_i2c_transfer(bus, msgs, 2);
        if (n == 2) {
            qe_printf("detected i2c device at %x\r\n", n);
        }
    }

    return qe_yield;
}

static void cmd_i2c(int argc, char *argv[])
{
    qe_ret ret;
    qe_str name;
    qe_argparse parser;
    qe_dev *dev;

    qe_option options[] = {
        QE_ACT_STRING('d', "dev", "set current i2c devices",
            &name, QE_NULL, action_set_current_device),
        QE_OPT_ACTION(QE_NULL, "detect", "i2c bus detect",
            QE_NULL, action_bus_detect),
        QE_OPT_HELP('h', "--help", "i2c help"),
        QE_OPT_END(),
    };

    qe_argp_init(&parser, options, usages,
    	"\ni2c command.",
		"\ni2c command.");

    qe_argp_parse(&parser, argc, (qe_const_str *)argv);
}
QE_SHELL_EXPORT_CMD_EXEC(i2c, cmd_i2c, i2c commands);

QE_SHELLCMD_FORCE_EXPORT(i2c);